package com.quan.bookmall.service.impl;

import com.quan.bookmall.dto.BookDTO;
import com.quan.bookmall.dto.CartItemDTO;
import com.quan.bookmall.entity.Book;
import com.quan.bookmall.entity.CartItem;
import com.quan.bookmall.repository.BookRepository;
import com.quan.bookmall.repository.CartItemRepository;
import com.quan.bookmall.service.CartService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityNotFoundException;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CartServiceImpl implements CartService {
    
    private final CartItemRepository cartItemRepository;
    private final BookRepository bookRepository;
    
    @Override
    public List<CartItemDTO> findByUserId(Long userId) {
        List<CartItem> cartItems = cartItemRepository.findByUserId(userId);
        return cartItems.stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }
    
    @Override
    @Transactional
    public CartItemDTO addToCart(Long userId, Long bookId, Integer quantity) {
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new EntityNotFoundException("书籍不存在"));
        
        if (book.getStock() < quantity) {
            throw new IllegalArgumentException("库存不足");
        }
        
        CartItem cartItem = cartItemRepository.findByUserIdAndBookId(userId, bookId)
                .orElse(new CartItem());
        
        if (cartItem.getId() == null) {
            cartItem.setUserId(userId);
            cartItem.setBookId(bookId);
            cartItem.setQuantity(quantity);
        } else {
            cartItem.setQuantity(cartItem.getQuantity() + quantity);
        }
        
        CartItem savedCartItem = cartItemRepository.save(cartItem);
        return convertToDTO(savedCartItem);
    }
    
    @Override
    @Transactional
    public CartItemDTO updateQuantity(Long userId, Long bookId, Integer quantity) {
        CartItem cartItem = cartItemRepository.findByUserIdAndBookId(userId, bookId)
                .orElseThrow(() -> new EntityNotFoundException("购物车项不存在"));
        
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new EntityNotFoundException("书籍不存在"));
        
        if (book.getStock() < quantity) {
            throw new IllegalArgumentException("库存不足");
        }
        
        cartItem.setQuantity(quantity);
        CartItem updatedCartItem = cartItemRepository.save(cartItem);
        return convertToDTO(updatedCartItem);
    }
    
    @Override
    @Transactional
    public void removeFromCart(Long userId, Long bookId) {
        CartItem cartItem = cartItemRepository.findByUserIdAndBookId(userId, bookId)
                .orElseThrow(() -> new EntityNotFoundException("购物车项不存在"));
        cartItemRepository.delete(cartItem);
    }
    
    @Override
    @Transactional
    public void clearCart(Long userId) {
        List<CartItem> cartItems = cartItemRepository.findByUserId(userId);
        cartItemRepository.deleteAll(cartItems);
    }
    
    private CartItemDTO convertToDTO(CartItem cartItem) {
        CartItemDTO cartItemDTO = new CartItemDTO();
        BeanUtils.copyProperties(cartItem, cartItemDTO);
        
        if (cartItem.getBook() != null) {
            BookDTO bookDTO = new BookDTO();
            BeanUtils.copyProperties(cartItem.getBook(), bookDTO);
            cartItemDTO.setBook(bookDTO);
        }
        
        return cartItemDTO;
    }
} 